package cn.toutatis.sandbox.filter.log;


import cn.toutatis.common.config.TimeConstant;
import cn.toutatis.common.log.LogBackHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * @author Toutatis_Gc
 */
@Component
@ConfigurationProperties(prefix = "void")
public class LogBackInterceptor implements HandlerInterceptor {

    private TimeConstant timeConstant  = TimeConstant.INSTANCE;

    private static final Logger logger = LoggerFactory.getLogger(LogBackInterceptor.class);

    @Value("${void.dev-mode:true}")
    private boolean devMode;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(devMode){
            if (handler instanceof HandlerMethod){
                HandlerMethod handlerMethod = (HandlerMethod)handler;
                Class<?> beanType = handlerMethod.getBeanType();
                synchronized (handler){
                    LogBackHandle annotation = beanType.getAnnotation(LogBackHandle.class);
                    SimpleDateFormat simpleDateFormat = timeConstant.simpleDateFormat;
                    logger.info("--------------------请求时间："+simpleDateFormat.format(new Date())+"--------------------");
                    logger.info("请求地址："+ request.getRequestURL().toString() +"\t请求类型："+ request.getMethod());
                    logger.info("请求类名："+beanType.getName()+"\t请求方法："+handlerMethod.getMethod().getName());
                    if (annotation != null) {logger.info("类简述："+annotation.value());}
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    if (parameterMap.size() != 0){
                        StringBuilder parameters = new StringBuilder();
                        for (Map.Entry<String, String[]> para : parameterMap.entrySet()) {
                            parameters.append(para.getKey()).append("=").append(Arrays.toString(para.getValue())).append("\t");
                        }
                        logger.info("请求参数："+parameters.toString());
                    }
                }
            }
        }
        return true;
    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
////        TODO 完成对响应内容的的日志记录(暂定)
//    }
}
